import { createRouter, createWebHistory } from 'vue-router'
import {useUserStore} from "../stores";


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {//登录、注册相关的路由
      path: '/login',
      name: '登录',
      component: ()=>import('../views/Login/Login.vue'),
      children:[
          {
            path: '/register',
            name: '注册',
            component: ()=>import('../views/Login/Register.vue'),
          }]
    },//管理员相关的
    {
      path: '/admin',
      component: ()=>import('../views/Admin/Admin.vue'),
      redirect:"/admin/adminMain",
      children:[
          {
            path: '/admin/adminMain',
            name: '主页',
            component: ()=>import('../views/Admin/AdminMain.vue'),
          },
          {
              path: '/admin/setGoods',
              name: '商店',
              component: ()=>import('../views/Admin/SetGoods.vue'),
          },
          {
              path: '/admin/setAdmin',
              name: '管理员',
              component: ()=>import('../views/Admin/SetAdmin.vue'),
          },
          {
              path: '/admin/setForum',
              name: '贴子',
              component: ()=>import('../views/Admin/SetForum.vue'),
          },
      ]
    },
    {
    //用户相关
      path:'/',
      component: ()=>import('../views/User/User.vue'),
      redirect:'/user/userMain',
      children:[
          {
            path: '/user/userMain',
            name: '首页',
            component: ()=>import('../views/User/UserMain.vue')
          },
          {
             path: '/user/shop',
             name: '商城',
             component: ()=>import('../views/User/shopping/Shop.vue'),

          },
          {
              path: '/user/shop/shopMain',
              name: '商品',
              component: ()=>import('../views/User/shopping/ShopMain.vue'),

          },
          {
            path: '/user/forum',
            name: '论坛',
            component: ()=>import('../views/User/forum/Forum.vue'),
          },
          {
              path: '/user/forum/detail',
              name: '帖子',
              component: ()=>import('../views/User/forum/Detail.vue')
          },
          {
              path: '/user/cart',
              name: '购物车',
              component: ()=>import('../views/User/shopping/ShopCart.vue')
          },
          {
              path: '/user/myShop',
              name: '我的发布',
              component: ()=>import('../views/User/shopping/Myshop.vue')
          }


      ]
    }


  ]
})

 // 全局守卫：登录拦截

router.beforeEach((to, from, next) => {
    //除了主页 登录页 注册页 其他都要有token
   if (to.path=='/user/userMain' || to.path=='/login' || to.path=='/register'){
       next()
   }else {
       const userStore = useUserStore()
      if (userStore.token==null){
          next('/login')
      }else {
          next()
      }
   }
});


export default router
